/**
 * Created by Administrator on 2017/3/21.
 */
import React, { Component,Fragment } from 'react';
import {
  Form,
  Input,
  DatePicker,
  Select,
  InputNumber,
  Button,
  Tooltip,
  Icon,
  Collapse,
  Upload,
  message,
  Modal
} from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import request from '@/utils/request';
import find from 'lodash/find';
import upload from './../../images/upload.png'
import deleteImg from './../../images/delete.png'
import ZImg from "react-zmage";
const { Panel } = Collapse;
const FormItem = Form.Item;
const Option = Select.Option;
let uuid = 10;
const { confirm } = Modal;
class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      meterArr: [1, 2, 3, 4, 5, 6, 7, 8],
      meterActiveKey: ['1', '2', '3', '4', '5', '6', '7', '8'],
      meter1: [],
      meter2: [],
      meter3: [],
      meter4: [],
      meter5: [],
      meter6: [],
      meter7: [],
      meter8: [],
      concentratorPicArr: [],
      port1PicArr: [],
      port2PicArr:[],
      port3PicArr:[],
      port4PicArr:[],
      port5PicArr:[],
      port6PicArr:[],
      port7PicArr:[],
      port8PicArr:[],
      fileList:[],
    };
  }


  componentDidMount() {
    const that = this;
    if(this.props.type==='config'){
      console.log(this.props.editRecord)
      // this.props.editRecord.meters=[{index:1,caliber:"DN100",initial_value:100},{index:2,caliber:"DN120",initial_value:10},{index:3,caliber:"DN10",initial_value:8}]
      this.setState({
        concentratorPicArr:this.props.editRecord.concentrator_images?this.props.editRecord.concentrator_images:[]
      })
      if(this.props.type==='config'&&this.props.editRecord&&this.props.editRecord.config&&this.props.editRecord.config.meter_config){
        for(let i in this.props.editRecord.config.meter_config){
          let item=this.props.editRecord.config.meter_config[i];
          let index=i.substr(4,1)
          that.props.form.setFieldsValue({
            [`meter_number-${index}`]:item.meter_number,
            [`caliber-${index}`]:item.caliber,
            [`initial_value-${index}`]:item.initial_value,
            [`dial_value-${index}`]:item.dial_value,
            [`remark-${index}`]:item.remark,
          })
          that.setState({
            [`port${index}PicArr`]:item.meter_images?item.meter_images:[]
          })
        }
      }
    }

  }

  deleteMeter = (item) => {
    console.log('删除的item', item);
    const that=this;
    if (this.state.meterArr.length === 1) {
      console.log('只有一个水表');
      // message.error('至少需要一个水表')
      // return false
    }
    // const index = this.state.meterArr.indexOf(item);
    // console.log('index', index);
    that.props.form.setFieldsValue({
      [`index-${item}`]:'',
      [`caliber-${item}`]:'',
      [`initial_value-${item}`]:'',
    })
  };

  render() {
    const formItemLayoutWithLabel = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    const that=this;
    const { getFieldDecorator } = this.props.form;
    const meterForms = this.state.meterArr.map((item, index) => {
      const props = {
        beforeUpload: (file) => {
          let formData = new FormData();
          formData.append("file", file);
          formData.append("group", 'concentrator_'+this.props.editRecord.number+'_'+(index+1));
          request(`/images`, {
            method: 'POST',
            data: formData
          }).then((response)=> {
            console.log(response);
            if(response.status===200){
              that.state[`port${index+1}PicArr`].push(response.data.data.path)
              that.setState({
                [`port${index+1}PicArr`]:that.state[`port${index+1}PicArr`]
              })

            }
          })
          return false;
        },
        showUploadList:false,
        accept:".png, .jpg, .jpeg"
      };
      return (
        <Panel header={`端口${index+1}`} key={(index+1).toString()}  >
          <Form style={{display:'flex'}}  layout="inline">
            <FormItem
              style={{ flex:1, marginRight: '0' }}
              label={'水表号'}
              {...formItemLayoutWithLabel}
            >
              {getFieldDecorator(`meter_number-${item}`, {
                initialValue: '',
              })(
                <Input disabled={true} style={{ width: '100%', fontWeight: 'bold' }}/>,
              )}
            </FormItem>
            <FormItem
              style={{ flex:1, marginRight: '0' }}
              label={'表底数'}
              {...formItemLayoutWithLabel}
            >
              {getFieldDecorator(`initial_value-${item}`, {
                initialValue: '0',
              })(
                <Input disabled={true} style={{ width: '100%', fontWeight: 'bold' }} addonAfter={'m³'}/>,
              )}
            </FormItem>
            <FormItem
              style={{ flex:1, marginRight: '0' }}
              label={'表盘数'}
              {...formItemLayoutWithLabel}
            >
              {getFieldDecorator(`dial_value-${item}`, {
                initialValue: '0',
              })(
                <Input disabled={true} style={{ width: '100%', fontWeight: 'bold' }} addonAfter={'m³'}/>,
              )}
            </FormItem>
            <FormItem
              style={{ flex:1, marginRight: '0' }}
              label={'口径'}
              {...formItemLayoutWithLabel}
            >
              {getFieldDecorator(`caliber-${item}`, {
                initialValue: 'DN15',
              })(
                <Select disabled={true}  style={{width:'100%',fontWeight:'bold'}}>
                  {[{key:'未知',value:'未知'},
                    {key:'DN15',value:'DN15'},
                    {key:'DN20',value:'DN20'},
                    {key:'DN25',value:'DN25'},
                    {key:'DN32',value:'DN32'},
                    {key:'DN40',value:'DN40'},
                    {key:'DN50',value:'DN50'},
                    {key:'DN65',value:'DN65'},
                    {key:'DN80',value:'DN80'},
                    {key:'DN100',value:'DN100'},
                    {key:'DN150',value:'DN150'},
                    {key:'DN200',value:'DN200'},
                    {key:'DN300',value:'DN300'},
                  ].map(function(item,index) {
                    return <Option key={index} value={item.key}>
                      {item.value}
                    </Option>
                  })}
                </Select>
              )}
            </FormItem>
            <FormItem
              style={{ flex:1, marginRight: '0' }}
              label={'备注'}
              {...formItemLayoutWithLabel}
            >
              {getFieldDecorator(`remark-${item}`, {
                initialValue: '',
              })(
                <Input disabled={true} style={{ width: '100%', fontWeight: 'bold' }}/>,
              )}
            </FormItem>


          </Form>
          <div style={{display:'flex',marginTop:'16px'}}>
            <div style={{width:'65px',marginRight:'9px',color:'#000',textAlign:'right'}}>
              水表照片:
            </div>
            <div style={{flex:1}}>
              {
                [this.state[`port${index+1}PicArr`].map(function (item2,index2){
                  return <div style={{position:'relative',display:'inline-block'}} key={index2}>
                    <ZImg style={{height:'100px',width:'100px',marginRight:'16px',marginBottom:'16px'}} src={item2} />
                    <img  src={deleteImg} style={{position:'absolute',right:'16px',top:'0',width:'40px',height:'40px',cursor:'pointer'}} onClick={()=>{
                      confirm({
                        title: `确定要删除该照片吗?`,
                        content: '请谨慎操作！',
                        okText: '确定',
                        okType: 'danger',
                        cancelText: '取消',
                        centered: true,
                        maskClosable: true,
                        onOk() {
                          let idx;
                          for (let i = 0; i < that.state[`port${index+1}PicArr`].length; i++) {
                            console.log(that.state[`port${index+1}PicArr`][i])
                            if (item2 === that.state[`port${index+1}PicArr`][i]) {
                              idx = i;
                              console.log(idx)
                              that.state[`port${index+1}PicArr`].splice(idx, 1)
                              that.setState({
                                [`port${index+1}PicArr`]: that.state[`port${index+1}PicArr`]
                              },function(){
                              })
                            }
                          }
                        },
                        onCancel() {
                          console.log('Cancel');
                        },
                      });
                    }} alt=""/>
                  </div>
                })]
              }
              <Upload {...props} >
                <img src={upload}   style={{height:'100px',width:'100px',marginRight:'16px',marginBottom:'16px',cursor:'pointer'}}alt=""/>
              </Upload>

            </div>
          </div>
        </Panel>

      );
    });
    const props = {
      beforeUpload: (file) => {
        let formData = new FormData();
        formData.append("file", file);
        formData.append("group", 'concentrator_'+this.props.editRecord.number);
        request(`/images`, {
          method: 'POST',
          data: formData
        }).then((response)=> {
          console.log(response);
          if(response.status===200){
            that.state[`concentratorPicArr`].push(response.data.data.path)
            that.setState({
              [`concentratorPicArr`]:that.state[`concentratorPicArr`]
            })

          }
        })
        return false;
      },
      showUploadList:false,
      accept:".png, .jpg, .jpeg"
    };
    return (
      <div>
        {
          <Fragment>
              <div style={{ marginTop: '10px' }}>

                <Collapse defaultActiveKey={['0','1','2','3','4','5','6','7','8']}>
                  <Panel header={`集中器`} key={'0'}  >
                    <Form layout="inline">
                      <div style={{display:'flex'}}  >
                        <FormItem
                          style={{ flex:1, marginRight: '0' }}
                          label={'集中器号'}
                          {...formItemLayoutWithLabel}
                        >
                          {getFieldDecorator(`number`, {
                            initialValue: this.props.editRecord.number,
                          })(
                            <Input disabled={true} style={{ width: '100%', fontWeight: 'bold' }}/>,
                          )}
                        </FormItem>
                        <FormItem
                          style={{ flex:1, marginRight: '0' }}
                          label={'IMEI'}
                          {...formItemLayoutWithLabel}
                        >
                          {getFieldDecorator(`imei`, {
                            initialValue: this.props.editRecord.imei,
                          })(
                            <Input  disabled={true} style={{ width: '100%', fontWeight: 'bold' }} />,
                          )}
                        </FormItem>
                        <FormItem
                          style={{ flex:1, marginRight: '0' }}
                          label={'平台'}
                          {...formItemLayoutWithLabel}
                        >
                          {getFieldDecorator(`platform`, {
                            initialValue: this.props.editRecord.config.platform,
                          })(
                            <Input  disabled={true} style={{ width: '100%', fontWeight: 'bold' }} />,
                          )}
                        </FormItem>


                      </div>
                      <div style={{display:'flex',width:'678px'}}>
                        <FormItem
                          style={{ flex:1, marginRight: '0' }}
                          label={'地址'}
                          {...formItemLayoutWithLabel}
                        >
                          {getFieldDecorator(`address`, {
                            initialValue:  this.props.editRecord.address,
                          })(
                            <Input style={{ width: '100%', fontWeight: 'bold' }} />,
                          )}
                        </FormItem>
                        <FormItem
                          style={{ flex:1, marginRight: '0' }}
                          label={'备注'}
                          {...formItemLayoutWithLabel}
                        >
                          {getFieldDecorator(`remark`, {
                            initialValue: this.props.editRecord.remark,
                          })(
                            <Input style={{ width: '100%', fontWeight: 'bold' }} />,
                          )}
                        </FormItem>
                      </div>

                    </Form>
                    <div style={{display:'flex',marginTop:'16px'}}>
                      <div style={{width:'90px',marginRight:'9px',color:'#000',textAlign:'right'}}>
                        集中器照片:
                      </div>
                      <div style={{flex:1}}>
                        {
                          [this.state[`concentratorPicArr`].map(function (item2,index2){
                            return <div style={{position:'relative',display:'inline-block'}} key={index2}>
                              <ZImg style={{height:'100px',width:'100px',marginRight:'16px',marginBottom:'16px'}} src={item2} />
                              <img  src={deleteImg} style={{position:'absolute',right:'16px',top:'0',width:'40px',height:'40px',cursor:'pointer'}} onClick={()=>{
                                confirm({
                                  title: `确定要删除该照片吗?`,
                                  content: '请谨慎操作！',
                                  okText: '确定',
                                  okType: 'danger',
                                  cancelText: '取消',
                                  centered: true,
                                  maskClosable: true,
                                  onOk() {
                                    let idx;
                                    for (let i = 0; i < that.state[`concentratorPicArr`].length; i++) {
                                      console.log(that.state[`concentratorPicArr`][i])
                                      if (item2 === that.state[`concentratorPicArr`][i]) {
                                        idx = i;
                                        console.log(idx)
                                        that.state[`concentratorPicArr`].splice(idx, 1)
                                        that.setState({
                                          [`concentratorPicArr`]: that.state[`concentratorPicArr`]
                                        },function(){
                                        })
                                      }
                                    }
                                  },
                                  onCancel() {
                                    console.log('Cancel');
                                  },
                                });
                              }} alt=""/>
                            </div>
                          })]
                        }
                        <Upload {...props} >
                          <img src={upload}   style={{height:'100px',width:'100px',marginRight:'16px',marginBottom:'16px',cursor:'pointer'}}alt=""/>
                        </Upload>

                      </div>
                    </div>
                  </Panel>

                  {meterForms}
                </Collapse>


            </div>

            </Fragment>
        }


      </div>

    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default connect()(AddPoliciesFormWrap);


